package net.sf.midollo.net.httptunnel.server;

import java.io.IOException;

import net.sf.midollo.net.protocol.ProtocolFactory;
import net.sf.midollo.utils.Map;
import net.sf.midollo.utils.Utils;

public class HttpTunnelServer {

  protected final ProtocolFactory protocolFactory;
  protected final Map sessions;
  protected long lastSessionId;

  public HttpTunnelServer(ProtocolFactory protocolFactory) throws IOException {
    this.protocolFactory = protocolFactory;
    this.sessions = Utils.newMap();
    this.lastSessionId = 0L;
  }

  public synchronized HttpTunnelServerSession createSession() throws IOException {
    String sessionId = Long.toString(++this.lastSessionId);
    HttpTunnelServerSession session = new HttpTunnelServerSession(this, sessionId, this.protocolFactory);
    this.sessions.put(sessionId, session);
    return session;
  }

  public synchronized HttpTunnelServerSession getSession(String sessionId) throws IOException {
    HttpTunnelServerSession session = (HttpTunnelServerSession)this.sessions.get(sessionId);
    if (session == null)
      throw new IOException("Invalid session id.");
    return session;
  }

  public synchronized void removeSession(HttpTunnelServerSession session) {
    this.sessions.remove(session);
  }
}
